#Makefile for MILOS

#current dir
CDIR:=.
#parent dir
PDIR:=.

CC=gcc
AS=as
CFLAGS=-nostdlib -nostdinc -fno-builtin -fno-stack-protector -g -MD -Wall -I ./include
LDFLAGS=-T tools/link.ld -g
ASFLAGS=-g 

OBJS:=
DEPS:= $(patsubst %.c,%.d,$(wildcard *.c))
#DEPS+=$(patsubst %.c,%.d,$(wildcard *.s))

#our colors
GREEN:="\e[32;1m"
RED:="\e[31;1m"
BLUE:="\e[34;1m"
TM_NULL:="\033[0m"

#qemu seems require boot.s link first
include boot/subdir.mk
include kernel/subdir.mk
include mm/subdir.mk
OBJS+=$(patsubst %.s,%.o,$(wildcard *.s))
OBJS+=$(patsubst %.c,%.o,$(wildcard *.c))

%.o:%.c
	@echo -e $(GREEN)"[CC]" $< $(TM_NULL)
	@$(CC) $(CFLAGS) -c $< -o $@
%.o:%.s
	@echo -e $(GREEN)"[AS]" $< $(TM_NULL)
	@$(AS) $(ASFLAGS) -c $< -o $@

all: kernel.bin

kernel.bin: $(OBJS)
	@echo -e $(RED)"Generating MILOS binary file..."$(TM_NULL)
	@ld $(LDFLAGS) -o kernel.bin $(OBJS)
	@echo -e $(RED)"Compilation completed!"$(TM_NULL)

qemu: kernel.bin
	qemu-system-i386 -kernel kernel.bin
dbg: kernel.bin
	qemu-system-i386 -kernel kernel.bin -S -s
bochs: floppy.img
	bochs -f tools/bochsrc.txt

disk: floppy.img

floppy.img: kernel.bin
	if [ ! -b /dev/loop0 ]; then sudo modprobe loop; fi
	sudo /sbin/losetup /dev/loop0 floppy.img
	sudo mount /dev/loop0 ./floppy/
	sudo cp ./kernel.bin ./floppy/kernel
	sudo umount /dev/loop0
	sudo /sbin/losetup -d /dev/loop0
	sync

clean:
	@rm $(OBJS) kernel.bin $(DEPS)
	@echo -e $(RED)"Clean: done!"$(TM_NULL)
-include $(DEPS)

